package com.niiwoo.civet.trade.service.local.databackflow.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.trade.dao.entity.DataBackflowStatus;
import com.niiwoo.civet.trade.dao.mapper.DataBackflowDetailsMapperExt;
import com.niiwoo.civet.trade.dao.mapper.DataBackflowStatusMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectLoanDeviceInfoMapperExt;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataStatusEnum;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataTypeEnum;
import com.niiwoo.civet.trade.service.local.databackflow.DataBackflowService;
import com.niiwoo.civet.user.dto.LinkManDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserPersonalDubboInfoDTO;
import com.niiwoo.civet.user.dto.response.UserBasicInfoResponseDTO;
import com.niiwoo.civet.user.enums.LinkManRelationEnum;
import com.niiwoo.civet.user.enums.TCFromTypeEnum;
import com.niiwoo.civet.user.enums.UserEnum;
import com.niiwoo.civet.user.enums.UserPersonalEnum;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.civet.user.service.UserDataDubboService;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.request.df.PersonalInfoRequest;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author wping
 * @Description: 个人基本信息回流监听器
 * @date 2018/4/18 17:19
 */
@Slf4j
@Component
public class PersonalInfoListener implements DataBackflowListener {

    @Autowired
    private DataBackflowStatusMapperExt dataBackflowStatusMapperExt;

    @Autowired
    private DataBackflowDetailsMapperExt dataBackflowDetailsMapperExt;

    @Autowired
    private ProjectLoanDeviceInfoMapperExt projectLoanDeviceInfoMapper;

    @Autowired
    private TianchengDataFlowService tianchengDataFlowService;

    @Autowired
    private DataBackflowService dataBackflowService;

    @Reference(version = "1.0.0")
    private UserDataDubboService userDataDubboService;

    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;

    @Override
    public void handle(Long flowExecuteId, String userId, Long projectId, int currentExecuteTimes) {

        final String methodName = "个人基本信息回流监听到回流请求, flowExecuteId:" + flowExecuteId + ", userId:" + userId + ", projectId:" + projectId;
        if (flowExecuteId == null || StringUtils.isEmpty(userId) || projectId == null) {
            log.error(methodName + "-flowExecuteId/userId/projectId为空");
            return;
        }

        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
        // 查询最近一次回流状态情况
        DataBackflowStatus dataBackflowStatus = dataBackflowStatusMapperExt.selectByUserIdProjectIdWithDataType(userId, projectId, DataBackflowStatusDataTypeEnum.PERSONAL_INFO.getType());
        if (dataBackflowStatus != null) {
            if (DataBackflowStatusDataStatusEnum.BACKFLOW_SUCCESSED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流，无需重复回流");
                return;
            }
            if (DataBackflowStatusDataStatusEnum.FAILED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流失败, 非待回流状态");
                return;
            }

            if (DataBackflowStatusDataStatusEnum.WAITING_BACKFLOW.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()
                    || DataBackflowStatusDataStatusEnum.FAILED_WITH_RETRY.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                try {

                    UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataDubboService.userPersonalInfo(userId);
                    if (userPersonalDubboInfoDTO == null) {
                        log.error(methodName + "-用户个人信息表不存在");
                        dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "用户个人信息表不存在");
                        return;
                    }

                    UserBasicInfoResponseDTO userBasicInfo = userBasicInfoDubboService.getUserBasicInfo(userId);
                    if (userBasicInfo == null) {
                        log.error(methodName + "-用户基本信息表不存在");
                        dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "用户基本信息表不存在");
                        return;
                    }

                    PersonalInfoRequest tianchengRequest = new PersonalInfoRequest();
                    tianchengRequest.setUserId(userId);//用户id
                    tianchengRequest.setMobilePhone(userBasicInfo.getMobileNo());//手机号
                    Integer eduLevel = UserPersonalEnum.UserEduLevelEnum.getByLevel(userPersonalDubboInfoDTO.getEducationLevel()).getTianChengUserEduLevelEnum().getType();
                    tianchengRequest.setDegreeType(eduLevel);//学历--学历类型(1大专以下,2大专,3本科,4硕士,5博士及以上)
                    Integer maritalStatus = UserPersonalEnum.UserMaritalStatusEnum.getByLevel(userPersonalDubboInfoDTO.getMaritalStatus()).getTianChengUserMaritalStatusEnum().getStatus();
                    UserEnum.RegisterChannel registerChannel = UserEnum.RegisterChannel.enumOf(userBasicInfo.getRegisterChannel().byteValue());
                    tianchengRequest.setFromType(TCFromTypeEnum.getTCFromTypeFromRegisterChannel(registerChannel)); ////用户来源(0-未知 1团贷网，2好帮贷，3你我金融，4房宝宝，5现金动车，6量化派 7 借钱快 8 融360 9卡牛)
                    tianchengRequest.setMaritalStatus(maritalStatus);//婚姻状况--(0未婚,1已婚,2离异,3丧偶)
                    tianchengRequest.setLivingProvince(userPersonalDubboInfoDTO.getLivingProvince());//现居住地址省份
                    tianchengRequest.setLivingCity(userPersonalDubboInfoDTO.getLivingCity());//现居住地址城市
                    tianchengRequest.setLivingArea(userPersonalDubboInfoDTO.getLivingArea());//现居住地址区
                    tianchengRequest.setLivingAddress(userPersonalDubboInfoDTO.getLivingAddress());//详细地址
                    tianchengRequest.setEmail(userPersonalDubboInfoDTO.getEmail());//电子邮箱
                    tianchengRequest.setUpdateTime(userPersonalDubboInfoDTO.getUpdateTime().getTime() * 1000L);//更新时间--微秒时间戳
                    //联系人初始化
                    this.personalInfoInitLinkManInfo(userPersonalDubboInfoDTO, tianchengRequest);

                    log.info(methodName + "-天称个人基本信息回流开始，请求参数={}", JSON.toJSONString(tianchengRequest));
                    CompletableFuture<TianchengUapResponse> completableFuture = tianchengDataFlowService.personalInfo(tianchengRequest);
                    completableFuture.whenComplete((s, t) -> {
                        // 成功
                        if (s != null) {
                            TianchengUapResponse tianchengUapResponse = (TianchengUapResponse) s;
                            //回流成功
                            if (tianchengUapResponse.isSuccess()) {
                                log.info(methodName + "-天称个人基本信息回流成功，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, true, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            } else {
                                //回流失败
                                log.info(methodName + "-天称个人基本信息回流失败，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            }
                        }
                        // 异常
                        if (t != null) {
                            log.error(methodName + "-天称个人基本信息回流异常，异常信息:{}", t);
                            dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, t.getMessage());
                        }
                    });
                } catch (Exception e) {
                    log.error(methodName + "-回流异常", e);
                    dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "未知异常");
                }
            }
        } else {
            log.error(methodName + "-未查询到DataBackflowStatus数据，请初始化数据...");
        }
    }

    //联系人初始化
    private void personalInfoInitLinkManInfo(UserPersonalDubboInfoDTO userPersonalDubboInfoDTO, PersonalInfoRequest tianchengRequest) {
        List<LinkManDubboInfoDTO> linkManInfoList = userPersonalDubboInfoDTO.getLinkManInfoList();
        if (CollectionUtils.isEmpty(linkManInfoList)) {
            return;
        }
        List<PersonalInfoRequest.UserRelationRequest> allUserRelations = new ArrayList<>();
        Map<String, PersonalInfoRequest.UserRelationRequest> nameAndMobileNoMap = new HashMap<String, PersonalInfoRequest.UserRelationRequest>();
        for (LinkManDubboInfoDTO linkMan : linkManInfoList) {
            PersonalInfoRequest.UserRelationRequest userRelationReq = new PersonalInfoRequest.UserRelationRequest();
            userRelationReq.setUserId(String.valueOf(userPersonalDubboInfoDTO.getUserId()));
            userRelationReq.setContactRelation(LinkManRelationEnum.getByEventType(linkMan.getRelation()).getDesc());
            userRelationReq.setContactName(linkMan.getName());
            userRelationReq.setContactPhone(linkMan.getMobileNo());
            userRelationReq.setUpdateTime(linkMan.getUpdateTime().getTime());
            nameAndMobileNoMap.put(linkMan.getName(), userRelationReq);
        }

        for (Map.Entry<String, PersonalInfoRequest.UserRelationRequest> entry : nameAndMobileNoMap.entrySet()) {
            allUserRelations.add(entry.getValue());
        }

//        List<PersonalInfoRequest.UserRelationRequest> userRelations = new ArrayList<>();
//        if (allUserRelations.size() > 2) {
//            userRelations.add(allUserRelations.get(0));
//            userRelations.add(allUserRelations.get(1));
//        } else {
//            userRelations.addAll(allUserRelations);
//        }

        tianchengRequest.setUserRelations(allUserRelations);
    }

    @Override
    public boolean isBackflowSuccess(String userId, Long projectId) {
        return dataBackflowService.isBackflowSuccess(userId, projectId, DataBackflowStatusDataTypeEnum.PERSONAL_INFO);
    }
}
